package tv.youxing.android.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import tv.youxing.android.R;
import tv.youxing.android.custom.CustomDialog;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.entity.HeadPostModel;
import tv.youxing.android.entity.MyInfoModel;
import tv.youxing.android.ui.BalanceActivity;
import tv.youxing.android.ui.CollectionActivity;
import tv.youxing.android.ui.DownloadAllActivity;
import tv.youxing.android.ui.FabulousActivity;
import tv.youxing.android.ui.FeedbackActivity;
import tv.youxing.android.ui.IntegralActivity;
import tv.youxing.android.ui.LoginActivity;
import tv.youxing.android.ui.MyMessageActivity;
import tv.youxing.android.ui.SettingsActivity;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.PhotoUtils;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

import static android.app.Activity.RESULT_OK;

/**
 * Created by apple on 2017/4/17.
 */

/**
 * 项目名：   youxing
 * 包名：     tv.youxing.android .fragment
 * 文件名：   MineFragment
 * 创建者：   叶克武
 * 创建时间： 2017/4/17 下午2:49
 * 描述：    TODO
 */
public class MineFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.avatar)
    CircleImageView avatar;
    @BindView(R.id.icon_vip)
    ImageView ivVIP;
    @BindView(R.id.guanzhu)
    TextView tv_guanzhu;
    @BindView(R.id.fenshi)
    TextView tv_fenshi;
    @BindView(R.id.tvName)
    TextView tvName;
    @BindView(R.id.tvStudy)
    TextView tvStudy;
    @BindView(R.id.tvContinue)
    TextView tvContinue;
    @BindView(R.id.tvMyMessage)
    ImageView tvMyMessage;
    @BindView(R.id.myMessage)
    LinearLayout myMessage;
    @BindView(R.id.ll_message)
    LinearLayout llMessage;
    @BindView(R.id.myPraise)
    LinearLayout myPraise;
    @BindView(R.id.ll_Fabulous)
    LinearLayout llFabulous;
    @BindView(R.id.myCollect)
    LinearLayout myCollect;
    @BindView(R.id.ll_Collection)
    LinearLayout llCollection;
    @BindView(R.id.loaded)
    LinearLayout loaded;
    @BindView(R.id.ll_downloads)
    LinearLayout llDownloads;
    @BindView(R.id.tvBalance)
    TextView tvBalance;
    @BindView(R.id.balance)
    LinearLayout balance;
    @BindView(R.id.ll_balance)
    LinearLayout llBalance;
    @BindView(R.id.tvScore)
    TextView tvScore;
    @BindView(R.id.ll_integral)
    LinearLayout llIntegral;
    @BindView(R.id.account)
    LinearLayout account;
    @BindView(R.id.ll_login)
    LinearLayout llLogin;
    @BindView(R.id.setting)
    LinearLayout setting;
    @BindView(R.id.ll_settings)
    LinearLayout llSettings;
    @BindView(R.id.suggestFeedback)
    LinearLayout suggestFeedback;
    @BindView(R.id.ll_feedback)
    LinearLayout llFeedback;
    @BindView(R.id.xx_status)
    LinearLayout xuexi_status;//学习状态


    //头像更新的相机操作
    private Button btn_camera;
    private Button btn_picture;
    private Button btn_cancel;

    MyInfoModel mMyInfoModel;


    @BindView(R.id.imageView)
    ImageView mImageView;





    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        ButterKnife.bind(this, view);
        initView(view);
        return view;
    }


    // 创建一个以当前系统时间为名称的文件，防止重复
    private File tempFile = new File(Environment.getExternalStorageDirectory(),
            getPhotoFileName());

    // 使用系统当前日期加以调整作为照片的名称
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");
        return sdf.format(date) + ".png";
    }

    private CustomDialog mDialog_avatar;


    void initView(View v) {
        mDialog_avatar = new CustomDialog(getActivity(), 400
                , ViewGroup.LayoutParams.MATCH_PARENT, R.layout.dialog_photo, R.style.Theme_dialog, Gravity.BOTTOM, R.style.pop_anim_style);
        mDialog_avatar.setCancelable(true);
        btn_camera = (Button) mDialog_avatar.findViewById(R.id.btn_camera);
        btn_camera.setOnClickListener(this);
        btn_picture = (Button) mDialog_avatar.findViewById(R.id.btn_picture);
        btn_picture.setOnClickListener(this);
        btn_cancel = (Button) mDialog_avatar.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
    }


    /**
     * 判断登录状态
     */
    void login() {
        if (ShareUtils.getBoolean(getContext(), AppConst.ISLOGIN, false)) {
            xuexi_status.setVisibility(View.VISIBLE);
            tv_guanzhu.setVisibility(View.VISIBLE);
            tv_fenshi.setVisibility(View.VISIBLE);
            tvBalance.setVisibility(View.VISIBLE);
            tvScore.setVisibility(View.VISIBLE);

            loadMyInfo();
        } else {
            ivVIP.setVisibility(View.GONE);
            xuexi_status.setVisibility(View.GONE);
            tv_guanzhu.setVisibility(View.GONE);
            tv_fenshi.setVisibility(View.GONE);
            tvMyMessage.setVisibility(View.GONE);
            tvBalance.setVisibility(View.GONE);
            tvScore.setVisibility(View.GONE);


            avatar.setImageResource(R.drawable.avater);
//            avatar.setClickable(false);
            llMessage.setClickable(false);
            llFabulous.setClickable(false);
            llCollection.setClickable(false);
            llDownloads.setClickable(false);
            llBalance.setClickable(false);
            llIntegral.setClickable(false);
            llLogin.setClickable(false);
            llSettings.setClickable(false);
            llFeedback.setClickable(false);


            tvName.setText("请先登录");
            tvName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
            });
            avatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(getContext(), LoginActivity.class));
                }
            });
        }


    }

    @Override
    public void onResume() {
        super.onResume();
        login();
    }


    @Override
    public void onPause() {
        super.onPause();
    }




    //我的详情
    void loadMyInfo() {
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));

        RxVolley.post(StaticClass.MyInfo, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                mMyInfoModel = GsonUtils.GsonToBean(t, MyInfoModel.class);

                if (mMyInfoModel.getCode() == AppConst.TOKENERROR) {
                    getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                    return;
                }

                if (!mMyInfoModel.getResult().getAvatar().equals("") && mMyInfoModel.getResult().getAvatar() != null) {
                    PicassoUtils.loadImageViewHolder(getContext(), mMyInfoModel.getResult().getAvatar(), R.drawable.avater, R.drawable.avater, avatar);
                }
//                ImageLoader.getInstance().displayImage(mMyInfoModel.getResult().getAvatar(),avatar);
                if (mMyInfoModel.getResult().getIs_authenticated() == 1) {
                    ivVIP.setVisibility(View.VISIBLE);
                } else {
                    ivVIP.setVisibility(View.GONE);
                }
                tvName.setText(mMyInfoModel.getResult().getUsername());
                tv_guanzhu.setText("关注 " + mMyInfoModel.getResult().getFollow_count() + "");
                tv_fenshi.setText("粉丝 " + mMyInfoModel.getResult().getFans_count() + "");
                //我的消息数
//                tvMyMessage.setText(mMyInfoModel.getResult().getInbox_unread()+"");
                if (mMyInfoModel.getResult().getNotification_unread() > 0) {
                    tvMyMessage.setVisibility(View.VISIBLE);
                } else {
                    if (tvMyMessage.getVisibility() == View.VISIBLE) {
                        tvMyMessage.setVisibility(View.GONE);
                    }
                }
                //账户余额
                tvBalance.setText(mMyInfoModel.getResult().getBalance() + "");
                //积分
                tvScore.setText(mMyInfoModel.getResult().getScore() + "");

                //学习时间
                tvStudy.setText(mMyInfoModel.getResult().getTotal_view_length_count());
                //学习天数
                tvContinue.setText(mMyInfoModel.getResult().getTotal_view_day_count());
            }
        });
    }


    @OnClick({R.id.avatar, R.id.ll_message, R.id.ll_Fabulous, R.id.ll_Collection,
            R.id.ll_downloads, R.id.ll_balance, R.id.ll_integral, R.id.ll_login,
            R.id.ll_settings, R.id.ll_feedback})
    public void click(View view) {

        switch (view.getId()) {
            case R.id.avatar:
                mDialog_avatar.show();
                break;
            case R.id.ll_message://我的消息
                startActivity(new Intent(getContext(), MyMessageActivity.class));
                break;
            case R.id.ll_Fabulous: //赞过的
                startActivity(new Intent(getContext(), FabulousActivity.class));
                break;
            case R.id.ll_Collection://收藏
                startActivity(new Intent(getContext(), CollectionActivity.class));
                break;
            case R.id.ll_downloads://已下载
                startActivity(new Intent(getContext(), DownloadAllActivity.class));
                break;
            //账户余额
            case R.id.ll_integral://积分
                startActivity(new Intent(getContext(), BalanceActivity.class));
                break;
            case R.id.ll_balance://余额
                startActivity(new Intent(getContext(), IntegralActivity.class));
                break;
            //设置
            case R.id.ll_settings:
                startActivity(new Intent(getContext(), SettingsActivity.class));
                break;
            //反馈
            case R.id.ll_feedback:
                startActivity(new Intent(getContext(), FeedbackActivity.class));
                break;
        }


    }


    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btn_camera:
                if (hasSdcard()) {
                    imageUri = Uri.fromFile(fileUri);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                        imageUri = FileProvider.getUriForFile(getContext(), "com.zz.fileprovider", fileUri);//通过FileProvider创建一个content类型的Uri
                        PhotoUtils.takePicture(this, imageUri, CODE_CAMERA_REQUEST);
                } else {
                    CustomToast.INSTANCE.showToast("设备没有SD卡");
                }
                break;
            case R.id.btn_picture:
                PhotoUtils.openPic(this, CODE_GALLERY_REQUEST);
                break;
            case R.id.btn_cancel:
                mDialog_avatar.dismiss();
                break;
        }
    }



    private static final int output_X = 480;
    private static final int output_Y = 480;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case CODE_CAMERA_REQUEST://拍照完成回调
                    cropImageUri = Uri.fromFile(fileCropUri);
                    PhotoUtils.cropImageUri(this, imageUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    break;
                case CODE_GALLERY_REQUEST://访问相册完成回调
                    if (hasSdcard()) {
                        cropImageUri = Uri.fromFile(fileCropUri);
                        Uri newUri = Uri.parse(PhotoUtils.getPath(getActivity(), data.getData()));
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                            newUri = FileProvider.getUriForFile(getActivity(), "com.zz.fileprovider", new File(newUri.getPath()));
                            PhotoUtils.cropImageUri(this, newUri, cropImageUri, 1, 1, output_X, output_Y, CODE_RESULT_REQUEST);
                    } else {
                        CustomToast.INSTANCE.showToast("设备没有SD卡");
                    }
                    break;
                case CODE_RESULT_REQUEST://裁剪完成后回调
                    Bitmap bitmap = PhotoUtils.getBitmapFromUri(cropImageUri, getActivity());


//                    Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null,null));
//                    Logger.d("uri:" + uri);


                    if (bitmap != null) {
                        if (mDialog_avatar.isShowing()) {
                            mDialog_avatar.dismiss();
                        }
                        headPost(bitmap);
                    }
                    break;
            }
        }
    }

    private void showImages(Bitmap bitmap) {
        avatar.setImageBitmap(bitmap);
    }

    /**
     * 头像上传
     */
    void headPost(final Bitmap bitmap) {
        int str_index = tempFile.getAbsolutePath().indexOf(".") + 1;//.的索引
        String img_type = tempFile.getAbsolutePath().substring(str_index);//图片的类型

        //post请求简洁版实现
        HttpParams params = new HttpParams();
        params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        params.put("avatar", "data:image/" + img_type + ";base64," + UtilTools.bitmapToBase64(bitmap));


        showProgress("上传中");

        RxVolley.post(StaticClass.HeadPost, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {
                HeadPostModel model = GsonUtils.GsonToBean(t, HeadPostModel.class);
                CustomToast.INSTANCE.showToast(model.getStatus());

                if (model.getCode() == AppConst.TOKENERROR) {
                    getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                    return;
                }

                if (model.getCode() == 200) {
                    CustomToast.INSTANCE.showToast("头像更新成功");
                    avatar.setImageBitmap(bitmap);
                    //文件地址名称
//                    Log.i("weizesong", tempFile.getAbsolutePath());
//                    Log.i("weizesong", tempFile.getAbsolutePath().lastIndexOf(".") +1+"");


                } else {
                    System.out.println(t);
                    CustomToast.INSTANCE.showToast("头像更新失败,请重新尝试");
                }



                hideProgress();
            }
        });
    }


    // 把裁剪后的图片保存到sdcard上
    private void saveCropPic(Bitmap bmp) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fis = null;
        bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
        try {
            fis = new FileOutputStream(tempFile);
            fis.write(baos.toByteArray());
            fis.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



//    *********************** 7.0 相机 ************************** //


    private static final int CODE_GALLERY_REQUEST = 0xa0;
    private static final int CODE_CAMERA_REQUEST = 0xa1;
    private static final int CODE_RESULT_REQUEST = 0xa2;
    private static final int CAMERA_PERMISSIONS_REQUEST_CODE = 0x03;
    private static final int STORAGE_PERMISSIONS_REQUEST_CODE = 0x04;
    private File fileUri = new File(Environment.getExternalStorageDirectory().getPath() + "/photo.jpg");
    private File fileCropUri = new File(Environment.getExternalStorageDirectory().getPath() + "/crop_photo.jpg");
    private Uri imageUri;
    private Uri cropImageUri;




    /**
     * 检查设备是否存在SDCard的工具方法
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);
    }
}
